/**
 * Created by Administrator on 2017-06-12.
 */
var index = {
    init : function(){
    	var setting = null;
    	this.base64 = new Base64();
        this.sliderH();         //计算左边栏高度
        this.treeTabInit = this.treeTab();          //初始化树切换函数
        this.detailInit = this.detail();            //初始化详情页tab切换
        this.detailGridInit = this.detailGrid();
        this.bind();
        this.vehicleCount();						//车辆总数和在线车辆数
        this.ztreeCreat();							//定义树结构
        this.initSubscribeTable();
        this.searchVehicle();						//初始化树
        this.carTree=null;                          //树对象
        this.vehicleArrayTimer=null;                //订阅定时器 
        this.arrayObj = new Array();
        mapTool.init();
        AMap.plugin(['AMap.ToolBar'],function(){
       	 mapTool.map.addControl(new AMap.ToolBar());
        });
        mapTool.drag({
        	h : 42,
        	callback : function(height){
        		index.myGrid.enableAutoHeight(true,height,true);
        		index.reloadGridData();
        	}
        });
        this.terminalMap = new HashMap();
        this.vehicleMap = new HashMap();
        this.vehicleID=null;
        this.GlobelVehicle = new HashMap();
        this.onlineVehicleStr = null;
        this.trafficLayer=null;
        this.uuidCache=new HashMap();
        this.allNum = new Array();
    	this.runNum = new Array();
      	this.stopNum = new Array();
      	this.droppedNum = new Array();
      	this.vehicleStatus = [0,0,0,0];
      	this.GlobelSubScribeVehicle=new HashMap();
      	this.GlobelSubScribeCommno=new HashMap();
      	this.subScriberTime=this.timer();
      	this.ImgUrlCache = new HashMap();
      	this.vehicleNoColor = new HashMap();
      	this.vehicleColor = new HashMap();
      	this.myGrid;
      	this.GlobalGpsCache=new HashMap();
      	this.GlobalVehilceNo=new HashMap();
      	this.GlobalAddress = new HashMap();
      	this.GlobalGridField = ['vehicleId','vehicleNo','vehicleChinaColor','accChainaStatus','carStatus','validS','gpsTimeS','gpsSpeedF','pulseSpeedF','gpsMileage','address'];
      	this.GlobalMarkerMatterCache = [];
      	this.isopenWin=false;
      	this.infoWindow=null;
      	this.MARKID=null;
    },

    /**
     * 计算各div高度的高度
     * */
    sliderH : function(){
        var winH = $(window).height();
        var sliderH = winH - 76;
        $('.content').css({
            'height' : sliderH + 'px'
        });
        $('.content').css({
        	'border-top':' 2px solid #2a5ab1'
        });

        var treeDivH = sliderH - 134;
        $('#carTreeList,.tree').height(treeDivH + 7);

        var mapH = sliderH - 225;
        $('#mymap').height(mapH);

        this.flexigridH = treeDivH- 22;
        this.mapH = mapH;
    },

    /**
     * 树切换
     * */
    treeTab : function(){
        var index = 0;
        $('.tree-title-list').click(function(){
            index = $(this).index();
            func(index);
        });
        var func = function(index){
        	$('.tree-title-list').find('a').removeClass('active');
        	$('.tree-title-list').eq(index).find('a').addClass('active')
            $('.tree-cont-list').hide().eq(index).show();
            $('.tree-title-line').css({
                left:50 * index + '%'
            });
            /*if(index == 1){
            	$('.car-details').show();
            }else{
            	$('.car-details').hide();
            }*/
        };
        var searchFunc = function(eq){
            index = eq;
            func(index);
        };
        return {
            searchFunc : searchFunc
        };
    },

    /**
     * 详情内容tab切换
     * */
    detail : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-details-title-list').removeClass('active').eq(index).addClass('active');
            $('.car-details-cont-list').removeClass('active').eq(index).addClass('active');
        };
        $('.car-details-title ').on('click','.car-details-title-list',function(){
            index = $(this).index();
            func(index);
        });
        var clickCar= function(eq){
            index = eq;
            func(index);
            
        };
        return {
            clickCar : clickCar,
            index : function(){
                return index;
            }
        }
    },
    /**
     * 订阅tab切换
     * */
    detailGrid : function(){
    	var _this = this;
        var index = 0;
        var func = function(index){
            $('.car-staues-list').removeClass('active').eq(index).addClass('active');
        };
        $('.car-staues-ul').on('click','.car-staues-list',function(){
            index = $(this).index();
            func(index);
            _this.subScribe(_this.arrayObj.toString());
        });
        return {
            index : function(){
                return index;
            }
        }
    },
    /**
     * 查看大图
     * */
    lookBigImg : function(){
        $('.lager-img').show();
        $('#mask').show();
    },
    vehicleCount : function(){
    	$.ajax({
    		type : 'post',
    		async : true,
    		url : appCtx+"/report/otherProvinceVe/getAllOnlineCount.html",
    		cache : false,
    		dataType : "JSON",
    		success : function(data){
    			if(data){
    				$("#onLineVeCount").html(data.onlineCount);
    				$("#allVehicleCount").html(data.allCount);
    			}
    		}
    	});
    },
    /**
     * 加载树
     * */
    ztreeCreat : function(){
        setting = {
            check : {
                enable : true,
                chkboxType : {
                    "Y" : "ps",
                    "N" : "ps"
                }
            },
            data : {
                key : {
                    name : "NAME"
                },
                simpleData : {
                    enable : true,
                    idKey : "ID",
                    pIdKey : "PID",
                    rootPId : 0
                }
            },
            callback : {
            	onCheck : index.zTreeOnCheck
//                onClick : index.zTreeOnClick,
//                onExpand : index.zTreeOnExpand
            }
        };
    },
    searchVehicle : function(){
    	//车牌号搜索条件
        var vehicle_no = $.trim($("#vehicle_no").val());
        $.ajax({
			type : 'post',
			async : true,
			data : {vehicle_no : vehicle_no},
			url : appCtx+"/report/otherProvinceVe/loadVehicleTree.html",
			cache : false,
			dataType : "JSON",
			success : function(data){
				if(data){
					index.carTree = $.fn.zTree.init($("#carTreeList"), setting, data.nodeList);
				}
			}
		});
    },
    /**
     * 当前用户车辆的上线状态
     */
    getVehicleStatus : function(tableData){
    	var getTimestamp=new Date().getTime();
        var _this = this;
        $.ajax({
            url : appCtx+'gis/monitor/queryVehicleStatus.html',
            data : {v:getTimestamp,enterpriseId:_this.enterpriseId},
            success : function(data){
                if(data){
                	var online= JSON.parse(data).online;
                	var offline;
                	var isonline = $('#vehicleSeachTable').find('.isonline');
                	for(var i=0;i<tableData.length;i++){
                		var da = tableData[i];
                		var indexs = online.indexOf(da.noColor);
                		if( indexs > -1){
                			da.noColor = online[indexs];
                			isonline.eq(i).removeClass('isonline_false').addClass('isonline_true');
                		}else{
                			da.noColor = online[indexs];
                			isonline.eq(i).removeClass('isonline_true').addClass('isonline_false');
                		}
                	}
                }
            }
        });
        //一分钟刷新一次车辆上线线
        setTimeout(function(){
            _this.getVehicleStatus(tableData);
        },6000*60);
	}, 
    /**
     *   刷新实时和基础面板
     * @param data
     */
    loadBaseInfo : function(data,grid,item){  
    	index.resetDetail();
    	var terminalID = data.TID;
    	var CommNO = data.CommNO;
		index.vehicleID=data.VID;
		 $(".car-track").removeAttr("disabled");
		 $(".car-video").removeAttr("disabled");
		 $(".car-num").text(data.NAME);
		 $(".car-remark").text(data.REMARK);
		 if(item){
			   $(".car-sd").text(item.gpsSpeedF);
	           	$(".car-millage").text(item.gpsMileageF);
	           	$(".car-time").text(item.gpsTimeS);
	       		$(".car-staue").text(item.status);
	       		$(".car-staue").attr("title",item.status);
	           	var address=mapTool.getAddress("caraddress",item);
	           	if(address){
	           		$("#caraddress").html(address);
	           	}
		 }
		 if(data.DNAME){
			 $(".car-driver").text(data.DNAME); 
		 }
		 if(data.PHONE){
			 $(".car-phone").text(data.PHONE);
		 }
		 if(grid){
			 
		 }else{
			 index.arrayObj.push(CommNO);
			 index.arrayObj=global.arr.removeRepeat(index.arrayObj);
			 index.subScribe(index.arrayObj.toString()); 
		 }	
    },
    
    /**
     * 初始化订阅表格
     */
    initSubscribeTable : function(){
    	var initOptions = [
        {	// 表格配置
           tableId:'gridbox',
           header:'操作,车牌号,车牌颜色,ACC,状态,精度,定位时间,速度,脉冲速度,里程,位置信息',
           colTypes:'cancelBtn,TrackingBtn,ro,ro,carStatus,ro,ro,ro,ro,ro,ro',
           code :'Handler,vehicleNo,vehicleChinaColor,accChainaStatus,carStatus,validS,gpsTimeS,gpsSpeedF,pulseSpeedF,gpsMileage,address',
           initWidths:'120,120,80,80,50,50,125,50,60,60,210',
           initWidthps:'120,120,80,80,50,50,125,50,60,60,510',
           align:'left,left,left,left,center,left,left,left,left,left,left',
           sort:',str,str,str,str,str,str,int,int,int,str'
    	 }];
    	 var obj = initOptions[0];
    	 index.myGrid = new dhtmlXGridObject(obj.tableId);
         //grid.setImagePath("../imgs/");//设置grid中引用图片路径，如排序图片，checkbox图片，背景等
    	 index.myGrid.setHeader('操作,车牌号,车牌颜色,ACC,状态,精度,定位时间,速度,脉冲速度,里程,位置信息',null,["text-align:left;","text-align:left;cursor:pointer;","text-align:left;","text-align:left;","text-align:left;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;cursor:pointer;","text-align:left;","text-align:left;"]);//列标题
    	 index.myGrid.setInitWidths(obj.initWidths);//各列宽度数字表示像素，弹性用*表示
    	 //index.myGrid.setInitWidthsP(obj.initWidthps)
    	 index.myGrid.setColumnIds(obj.code);
    	 index.myGrid.setColAlign(obj.align);//设置列数据的水平布局
    	 index.myGrid.setColTypes(obj.colTypes);//设置列数据的数据类型(ch ---- checkbox; ra ---- radio;ro ---- readonly，双击具体某项数据时不可编辑的;txt ---- 显示的是字符串，双击某项数据会弹出编辑页面 )
    	 index.myGrid.setColSorting(obj.sort);
    	 index.myGrid.setSkin("dhx_skyblue");//指明使用什么皮肤
    	 index.myGrid.enableAutoHeight(false,'auto',true);
    	 //index.myGrid.enableAutoHeight(false);
    	 //index.myGrid.enableAutoWidth(true);
    	 index.myGrid.init();
    	 index.myGrid.enablePreRendering(30);
    	 index.myGrid.enableSmartRendering(true);  //
    	 index.myGrid.attachEvent("onRowSelect",function(id,ind){
    	 var jsonData = index.GlobelSubScribeVehicle.get(id);		
    		if(jsonData){
    			var item = index.GlobelVehicle.get(id);
//    			index.loadBaseInfo(item,"grid");
    			mapTool.setCenter(jsonData);
    			index.detailInit.clickCar(0);
    			$(".car-sd").text(jsonData.gpsSpeedF);
	           	$(".car-millage").text(jsonData.gpsMileageF);
	           	$(".car-time").text(jsonData.gpsTimeStr);
	       		$(".car-staue").text(jsonData.status);
	       		$(".car-staue").attr("title",jsonData.status);
	           	var address=mapTool.getAddress("caraddress",jsonData);
	           	if(address){
	           		$("#caraddress").html(address);
	           		$("#caraddress").attr("title",address);
	           	}
    		}
    	 });
    },
    
    /**
     * 订阅（树）
     * @param e
     * @param treeId
     * @param treeNode
     */
    zTreeOnCheck : function(e, treeId, treeNode){
    	if (treeNode.LEVEL == 2) {// 根节点
    		var vehicle_no_color = treeNode.VID;
    		var vehicleID = treeNode.ID;
    		if (treeNode.checked) {
    			index.vehicleNoColor.put(vehicleID,vehicle_no_color);
    			index.arrayObj.push(vehicle_no_color);
    			index.arrayObj=global.arr.removeRepeat(index.arrayObj);
    			index.subScribe(index.arrayObj.toString());
//    			$("#ck_"+vehicleID).attr("checked", "checked");
    		} else {
    			global.arr.removeElm(index.arrayObj,vehicle_no_color);
    			index.subScribe(index.arrayObj.toString()); //取消之后的重新订阅 
//    			$("#ck_"+vehicleID).removeAttr("checked");
    			mapTool.clearMarker(vehicleID);
    			index.GlobalGpsCache.remove(vehicleID);
    			
    			if(index.arrayObj.length>0){
//					index.subScribe(index.arrayObj.toString());
				}else{
					index.vehicleStatus=[0,0,0,0];	
					$(".all-num").text(index.vehicleStatus[0]);
					$(".run-num").text(index.vehicleStatus[1]);
					$(".stop-num").text(index.vehicleStatus[2]);
					$(".dropped-num").text(index.vehicleStatus[3]);
					if(index.MARKID){
						index.MARKID=null;
        				index.infoWindow.close();
        			}
				}
    		}
    	}
    },
    /**
     * 重置实时和基础信息
     */
    resetDetail : function(){
    	$(".car-num").text("");
   	 	$(".car-sd").text("");
   	 	$(".car-millage").text("");
   	 	$(".car-time").text("");
   	    $(".car-staue").text("");
   	    $(".car-remark").text("");
   	    $(".car-driver").text("");
   	    $(".car-phone").text("");
   	    $(".car-address").text(""); 	 
    },
    /**普通查询*/
    searchTable : function(){
        var sarchVal = $.trim($('.search-input').val());
        var paramsGrid = [{
            name : 'vehicle_no',
            value : sarchVal
        }];
        $("#vehicleSeachTable").flexOptions({
    		url : appCtx+'/report/otherProvinceVe/queryOtherProVeByNo.html',
    		newp : 1,// 设置起始页
    		params : paramsGrid
    	}).flexReload();// 重新加载  
    },
    /**
     * 勾选订阅
     */
    subScribe : function(params){
   	 var getSubScribeDataVehicles = function(params){
   		 if(params == ""){
   			 index.cancelAll();
   			 return;
   		 }
   		 var getTimestamp=new Date().getTime();
   		 $.ajax({
              url : appCtx+'report/otherProvinceVe/subScribe.html',
              data : {"vehicle_no_color":encodeURI(params),v:getTimestamp},
              dataType :'json',
              success : function(data){
                  if(data){ 
                	    $("#cancel").css("display","block");
	                  	index.vehicleStatus=[0,0,0,0];
	               		index.vehicleStatus[0]=data.length;
	               		index.allNum=new Array();
	               		index.runNum=new Array();
	               		index.stopNum=new Array();
	               		index.droppedNum=new Array();
	               		index.GlobalGpsCache.clear();
	               		for(var i=0;i<data.length;i++){ 
	               			if(index.GlobalAddress.get(data[i].vehicleId)){
	               				data[i].address=index.GlobalAddress.get(data[i].vehicleId);
	               			}
	               			mapTool.clearMarker(data[i].vehicleId);
	             			index.addMarker(data[i]);
	             			index.allNum.push(data[i]);
	               			if(data[i].carStatus==1){
	               				index.runNum.push(data[i]);
	               				index.vehicleStatus[1]++;
	               			}else if(data[i].carStatus==2){
	               				index.stopNum.push(data[i]);
	               				index.vehicleStatus[2]++;
	               			}else{
	               				index.droppedNum.push(data[i]);
	               				index.vehicleStatus[3]++;
	               			};
	               			
	               			if(data[i].vehicleId==index.vehicleID){
	               				 $(".car-sd").text(data[i].gpsSpeedF);
		                    	 $(".car-millage").text(data[i].gpsMileageF);
		                    	 $(".car-time").text(data[i].gpsTimeS);
	                    		 $(".car-staue").text(data[i].status);
	                    		 $(".car-staue").attr("title",data[i].status);
		                    	 var address=mapTool.getAddress("caraddress",data[i]);
		                    	 if(address){
		                    		 $("#caraddress").html(address);
		                    	 }
	               			};
	               			data[i].vehicleChinaColor = global.carColor(data[i].vehicleColor);
	               			data[i].accChainaStatus = data[i].accStatus ? 'ACC开' : 'ACC关';
	               			if(index.detailGridInit.index()==0){
	               				index.handTrack(data[i]);
	               			}else if(index.detailGridInit.index()==1){
	               				if(data[i].carStatus==1){
	               					index.handTrack(data[i]);
	               				}
	               			}else if(index.detailGridInit.index()==2){
	               				if(data[i].carStatus==2){
	               					index.handTrack(data[i]);
	               				}
	               			}else if(index.detailGridInit.index()==3){
	               				if(data[i].carStatus==3){               					
	               					index.handTrack(data[i]);
	               				}
	               			}		
	               			index.GlobelSubScribeVehicle.put(data[i].vehicleId,data[i]);
//	               			if(data[i].vehicleId==0){
//	               				console.log("后端返回vehicleId=0  需要处理redis缓存数据的  终端ID 为： "+data[i].terminalId);
//	               			}
	               		}
	               		index.reloadGridData();
	               		$(".all-num").text(index.vehicleStatus[0]);
	               		$(".run-num").text(index.vehicleStatus[1]);
	               		$(".stop-num").text(index.vehicleStatus[2]);
	               		$(".dropped-num").text(index.vehicleStatus[3]);
                  }else{
	                 	var vehicleStatus=[0,0,0,0];
	                    $(".all-num").text(vehicleStatus[0]);
	               		$(".run-num").text(vehicleStatus[1]);
	               		$(".stop-num").text(vehicleStatus[2]);
	               		$(".dropped-num").text(vehicleStatus[3]);
	               		clearInterval(index.vehicleArrayTimer);
                  }
              }
          });
        };
     getSubScribeDataVehicles(params);
     clearInterval(index.vehicleArrayTimer);
   	 index.vehicleArrayTimer = setInterval(function(){
   		 getSubScribeDataVehicles(params);
   	 },30000);
    },
    /**
     * 处理定位数据
     */
    handTrack : function(jsonData){
//    	var GlobalGridField = ['vehicleId','vehicleNo','carStatus','validS','gpsTimeStr','gpsSpeedF','pulseSpeedF','gpsMileageF','status','address'];
    	var tmpData = [],tmpValue = null;
    	for(var i = 0; i < index.GlobalGridField.length; i++){
    		tmpValue = jsonData[index.GlobalGridField[i]];

    		if(tmpValue != undefined && tmpValue != null)
    			tmpData.push(tmpValue);
    		else
    			tmpData.push("");
    	}
    	var gridData = {id:jsonData.vehicleId,data:tmpData};
    	index.GlobalGpsCache.put(jsonData.vehicleId,gridData);
    },
    timer : function(){
    	 var subscribetimer;
    	 var funstart = function(){
    		 subscribetimer=setInterval(function(){
        		 index.subScribe();
        	 },20000); 
    	 }
    	 var funend = function(){
    		 clearInterval(subscribetimer);
    	 }
    	 return {
    		 funstart:function(){funstart();},
    		 funend:function(){funend();}
    	}
    	
    },
    /**
     * 导出
     */
    exportExcel : function(){
    	var result = '';
    	if(index.myGrid != undefined){
    		var idArray = index.myGrid.getAllRowIds().split(",");
    		for(var i = 0; i < idArray.length; i++){
    			index.myGrid.forEachCell(idArray[i],function(cellObj,ind){
    				if (ind > 0) {
    					if(1 == ind){
    						var htmls  = cellObj.getValue().match(/>\S+\</);
    						if (htmls!=null) {
    							result += htmls[0].replace(/[<|>]/g,"") + '#';
    						}
    					}else if(2 == ind){
    						var htmls  = cellObj.getValue().match(/>\S+\</);
    						if (htmls!=null) {
    							var temp = htmls[0].replace(/[<|/>]/g,"").replace("div","");
    							if(temp==1){
    								temp="运行";
    							}else if(temp==2){
    								temp="停车";
    							}else if(temp==3){
    								temp="掉线";
    							}
    							result += temp + '#';
    						}
    					}else{
    						result += cellObj.getValue() + '#';
    					}
    				}
                });
                result += '&';
            }
    		if(result.length > 0){
    			index.exportExc(appCtx+"gis/monitor/exportExcel.html?time="+ new Date(), {data:result,name:"Monitor"});
    		}else{
    			global.ajaxLoading.pop("暂无数据可导出",false,1000);
    		}
    	}else{
    		global.ajaxLoading.pop("该表不支持导出!",false,1000);
    	}
    },
    /**
     * 导出拼装
     * @param url
     * @param params
     */
    exportExc : function(url, params) {    
        var temp = document.createElement("form");        
        temp.action = url;        
        temp.method = "post";        
        temp.style.display = "none";  
        
        var opt1 = document.createElement("input");        
        opt1.name = "name";        
        opt1.value = params.name;
        opt1.type = "hidden";
        temp.appendChild(opt1); 
        
        
        var subLocationArrays = index.getSubParams(params.data);
        for (var i = 0; i < subLocationArrays.length; i++) {        
            var opt = document.createElement("input");        
            opt.name = "subData"+i;        
            opt.value = (subLocationArrays[i]).join("&");        
            temp.appendChild(opt);        
        }   
        document.body.appendChild(temp);   
        temp.submit();        
    },
    /**
     * 导出数据处理
     * @param data
     * @returns {Array}
     */
    getSubParams : function(data) {
    	var locationRows = data.split("&");
    	var i = locationRows.length / 100;
    	var subLocationRows = new Array();
    	for (var j = 0;j < i ; j++) {
    		subLocationRows.push(locationRows.slice(j*100,(j+1)*100));
    	}
    	return subLocationRows;
    },
    /**
     * 增加覆盖物
     * @param map
     * @param lon
     * @param lat
     */
	 addMarker : function(data){
		if(data.carStatus == 1){
			data.status = '运行';
		}else if(data.carStatus == 2){
			data.status = '停车';
		}else{
			data.status = '掉线';
		}
		var picUrl = mapTool.getVehicleStatusPicUrl(data.head,data.carStatus);
		marker = new AMap.Marker({
	        map: mapTool.map,
	        position: [data.longitude, data.latitude],
	        icon: picUrl,
	        offset: new AMap.Pixel(-15, -10),
	        autoRotation: true
	    });
		marker.setLabel({//label默认蓝框白底左上角显示，样式className为：amap-marker-label
	        offset: new AMap.Pixel(20, 20),//修改label相对于maker的位置
	        content: data.vehicleNo
	    });
		marker.content = '车牌号：'+data.vehicleNo+'('+global.carColor(data.vehicleColor)+')'+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileage+'公里</br>定位时间：'+data.gpsTimeS+'</br>状态：'+data.status;
		if(index.infoWindow&&index.MARKID==data.vehicleId){
			index.infoWindow.on('close',function(){
				//index.infoWindow=null;
				index.MARKID = null;
			}); 
		}
		
		marker.on('click', function(e){
			index.infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, 0)});
			index.isopenWin=true;
			var item = index.GlobelVehicle.get(data.vehicleId);
//			index.loadBaseInfo(item,'grid',data);
			index.detailInit.clickCar(0);
			index.MARKID=data.vehicleId;
			index.infoWindow.setContent(e.target.content);
			index.infoWindow.open(mapTool.map, e.target.getPosition());
			setTimeout(function(){
				index.MARKID=data.vehicleId;
			},500);
			
		});
		if(index.infoWindow&&index.MARKID==data.vehicleId){
			var mark = mapTool.initHashMap.GlobalMarkerCache.get(index.MARKID);
			//mark.content = '车牌号：'+data.vehicleNo+'</br>速度：'+data.gpsSpeedF+' 公里/小时</br>里程：'+data.gpsMileageF+'公里</br>定位时间：'+data.gpsTimeStr+'</br>状态：'+data.status;
			//index.infoWindow.setContent(mark.content);
			index.infoWindow.setContent(marker.content);
			index.infoWindow.open(mapTool.map,[data.longitude, data.latitude]);
		};
		mapTool.initHashMap.GlobalMarkerCache.put(data.vehicleId,marker);
	},
	/**
	 * 订阅全部取消
	 */
	cancelAll : function(){
		index.myGrid.clearAll();
		index.GlobalGpsCache.clear();
		index.arrayObj = new Array();
		mapTool.clearAllMarker();
		clearInterval(index.vehicleArrayTimer); 
		$("#cancel").css("display","none");
		index.carTree.checkAllNodes(false);
		var checks = $("#vehicleSeachTable").getCheckedRows();
		for(var i=0;i<checks.length;i++){
			$("#ck_"+checks[i]).removeAttr("checked");
		}		
		index.vehicleStatus=[0,0,0,0];		
		$(".all-num").text(index.vehicleStatus[0]);
		$(".run-num").text(index.vehicleStatus[1]);
		$(".stop-num").text(index.vehicleStatus[2]);
		$(".dropped-num").text(index.vehicleStatus[3]);
		if(index.MARKID){
			index.MARKID=null;
			index.infoWindow.close();
		}
	},
	/**
	 * 加载订阅表格
	 */
	reloadGridData : function(data){
		 var getAddressCallback = function(address,jsonData){
	    	 if(jsonData == null || !jsonData.hasOwnProperty("vehicleId") ) return;
	    		jsonData.address = address;
	    		var gpsJson = index.GlobalGpsCache.get(jsonData.vehicleId);
	    		if(gpsJson != null){
	    			gpsJson.data[index.GlobalGridField.indexOf("address")] = address;
	    			index.GlobalGpsCache.put(jsonData.vehicleId,gpsJson);
	    		}
	    		if(index.GlobalGridField.indexOf("address")>0){
//	    			index.reloadGridData();
	    			index.myGrid.cells(jsonData.vehicleId,index.GlobalGridField.indexOf("address")).setValue(address);
	    		}   		
	    		//{resTime:解析时间（毫秒表示）,address:解析的地址}
	    		//var obj = {resTime:new Date().getTime(),address:address};
	    		index.GlobalAddress.put(jsonData.vehicleId,address);
	     }
		index.myGrid.clearAll();
		if(!data){
			data = {
				rows:index.GlobalGpsCache.values()
			};
		}
		index.myGrid.parse(data,"json");
		var entitys = data.rows;
		for(var i=0;i<entitys.length;i++){
			var jsonData = index.GlobelSubScribeVehicle.get(entitys[i].id);
			mapTool.getAddressExtend(null,jsonData,getAddressCallback);
		}		 
	},
    bind : function(){
		var _this = this;
		var mapW = $('#mymap').width();
		//地图全屏
		$('#mapAllLi').click(function(){
			if($(this).hasClass('active')){
				$(this).removeClass('active');
				$('.content').css({
					'margin-left':'300px'
				});
				$('#mymap').css({
					width:mapW,
					height:_this.mapH
				});
				$('.header,.slider,.car-staues').show();
			}else{
				$(this).addClass('active');
				$('.content').css({
					'margin-left':0
				});
				$('#mymap').css({
					width:$('body').width(),
					height:$('body').height()
				});
				$('.header,.slider,.car-staues').hide();
			}
			
		});
		
        //显示更多车辆详情
        $('.car-btn-hide').click(function(){
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                $('.detail-more').hide();
            }else{
                $(this).addClass('active');
                $('.detail-more').show();
            }
        });

        //隐藏更多车辆详情
        $('.close-detail-more').click(function(){
            $('.car-btn-hide').removeClass('active');
            $('.detail-more').hide();
        });

        $('.look-bigimg').click(function(){
            _this.lookBigImg();
        });

        $('.lager-img').find('.close-pop').click(function(){
            $('.lager-img').hide();
            $('#mask').hide();
        });
        
        var searchFunc = function(){
        	var sarchVal = $.trim($('.search-input').val());
        	if(sarchVal){
        		_this.searchTable();
        	}else{
        		global.ajaxLoading.pop("请输入车牌号",false,1000);
        	}      	
        	_this.treeTabInit.searchFunc(1);
        };
        
        $('.search-btn').click(function(){
        	index.searchVehicle();
        });
        
        document.onkeydown=function(event){
            if(event.keyCode == 13){
            	searchFunc();
            }
        }
        
        $('.export').find('.icon-export').click(function(){	
        	index.exportExcel();
        });
        
        $('.export').find('.icon-cancel').click(function(){	
        	index.cancelAll();
        });
        
        $('.car-track').click(function(){
        	if(index.vehicleID){
        		if(index.GlobelVehicle.get(index.vehicleID).isPublicNet>0){
        			 var url = appCtx+"video/hisVideo.html?vehicleID="+index.vehicleID;
               		 window.open(url,"_blank");
        		}else{
        			global.ajaxLoading.pop("所选车辆不支持视频",false,1000);
        		}   		
        	}else{
        		global.ajaxLoading.pop("请选择车辆",false,1000);
        	}
   		
        });
        
        $('.car-trackplay').click(function(){
        	if(index.vehicleID){
        		var url = appCtx+"gis/playback/trackPlayBack.html?vehicleId="+index.vehicleID;
          		window.open(url,"_blank");	
        	}else{
        		global.ajaxLoading.pop("请选择车辆",false,1000);
        	}
        });
	
		 $("#listMap").click(function(){
			 var url = appCtx+"gis/matter/logisticsMap.html";
    		 window.open(url,"_blank"); 
		 });
		 
		 $("#mTrafficLi").toggle(function(){
			 index.trafficLayer = new AMap.TileLayer.Traffic({zIndex:10}); //实时路况图层
			 index.trafficLayer.setMap(mapTool.map);
			 $('.t8').addClass("active");
		 },function(){
			 index.trafficLayer.setMap(null);
			 $('.t8').removeClass("active");
		 });
		 
		 $("#distanceLi").click(function(){
			  mapTool.map.plugin(["AMap.RangingTool"], function() {
			     ruler = new AMap.RangingTool(mapTool.map);
		         AMap.event.addListener(ruler, "end", function(e) {
		            ruler.turnOff();
		            $('.t6').removeClass("active");
		         });
		         ruler.turnOn();
		         $('.t6').addClass("active");
			  });
		 });
		 
		 $("#showMap").toggle(function(){  //展示地物点
			 $('.t13').addClass("active");
			 index.customPointShow();
//			 index.customLineShow();
//			 index.customMapShow();
		 },function(){     //关闭地物点
			 $('.t13').removeClass("active");
			// $('.t13').css("background-color","rgb(255, 255, 255)");
			 mapTool.map.remove(index.GlobalMarkerMatterCache);
			 index.GlobalMarkerMatterCache=[];
		 });
		 
		 /*
		  * 左边定位树显示隐藏
		  */
		 $('#hideTree').click(function(){
			 var initWidthps = '11,11,5,5,12,5,5.5,5.5,19,20';
			 var initWidths = '120,120,50,50,125,50,60,60,200,210';
			 if($(this).hasClass('active')){
				 $(this).removeClass('active');
				 $('.slider').animate({'left':0},300);
				 $('.content').animate({'margin-left':'300px'},300,function(){
					 //index.myGrid.setInitWidths(initWidthps);
					 index.myGrid.setColWidth(9,210);
					 index.myGrid.setSizes();
				 });
				 
			 }else{
				 $(this).addClass('active');
				 $('.slider').animate({'left':'-300px'},300);
				 $('.content').animate({'margin-left':0},300,function(){
					 //index.myGrid.setInitWidthsP(initWidthps);
					 //index.myGrid.setInitWidths('120,120,50,50,125,50,60,60,200,510');
					 index.myGrid.setColWidth(9,510);
					 index.myGrid.setSizes();
				 });
			 }
		 });
		 
		 $("#copyVehicleUrlBtn").click(function(){
	    		var value = $("#vehicleShareurl_text").text();
	    		if(value){
	    			_this.copy();
	    		}else{
	    			 global.ajaxLoading.pop("无分享的链接复制！",true,1000);
	    		}
	    }); 
     },
     copy : function(){
 		var c1 = new ClipBoard({
 		    handlerID: 'copyVehicleUrlBtn',
 		    textID: 'vehicleShareurl_text',
 		    isAttr: false,
 		    type:'copy'
 		});
 		c1.attach(); // 触发复制/剪切功能
 	},
	addMatterMarker:function(longitude,latitude,content,iconUrl){
		var infoWindow = new AMap.InfoWindow({offset: new AMap.Pixel(0, -30)}); 
		var marker = new AMap.Marker({
	       position: [longitude,latitude],
	       icon: iconUrl
		});
		marker.setMap(mapTool.map);
		marker.content =content;
		marker.on('click', function(e){
			 infoWindow.setContent(e.target.content);
		     infoWindow.open(mapTool.map, e.target.getPosition());
		});

		index.GlobalMarkerMatterCache.push(marker);

	}
};

index.init();
function showVideo(vehicleId){
 	var url = appCtx+"video/videoMonitor.html?vehicleID="+vehicleId;
 	window.open(url,"_blank"); 
};
function showTrack(vehicleId){
	var url = appCtx+"gis/playback/trackPlayBack.html?vehicleId="+vehicleId;
	window.open(url,"_blank");
};
function cancelTrack(vehicleId){
	//var vehileNode = index.carTree.getNodesByParam("VID", vehicleId, null);
	/*index.carTree.checkNode(vehileNode[0], false, true);*/
	//global.arr.removeElm(index.arrayObj,index.terminalMap.get(vehileNode[0].VID));
	var vehicleNoColor = index.vehicleNoColor.get(vehicleId);
	global.arr.removeElm(index.arrayObj,vehicleNoColor);
	mapTool.clearMarker(vehicleId);
	index.myGrid.deleteRow(vehicleNoColor);
	index.GlobalGpsCache.remove(vehicleId);
//	$("#ck_"+vehicleId).removeAttr("checked");
	//$('#' + vehicleId).find('input').checked = false;
	
	//获取树复选框
	var node = index.carTree.getNodeByParam("ID", vehicleId, null);
	node.checked=false;
	index.carTree.updateNode(node);
	
	index.vehicleStatus[0]--;
	if(index.GlobelSubScribeVehicle.get(vehicleId)){
		var carStatus = index.GlobelSubScribeVehicle.get(vehicleId).carStatus;
		if(carStatus==1){
			index.vehicleStatus[1]--;
		}else if(carStatus==2){
			index.vehicleStatus[2]--;
		}else if(carStatus==3){
			index.vehicleStatus[3]--;
		}
	}	
	if(index.arrayObj.length>0){
		index.subScribe(index.arrayObj.toString());
	}else{
		clearInterval(index.vehicleArrayTimer);
		index.GlobalGpsCache.clear();
		index.myGrid.clearAll();
		index.vehicleStatus=[0,0,0,0];
		if(index.MARKID){
			index.MARKID=null;
			index.infoWindow.close();
		}
	}
	$(".all-num").text(index.vehicleStatus[0]);
	$(".run-num").text(index.vehicleStatus[1]);
	$(".stop-num").text(index.vehicleStatus[2]);
	$(".dropped-num").text(index.vehicleStatus[3]);	
}

//订阅列表
function eXcell_TrackingBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var noColor = val + '_' + index.vehicleColor.get(val);
		var str = index.base64.encode(noColor);
		//str = b.decode(str);
//		this.setCValue('<a href="'+appCtx+'gis/monitor/vehicleMonitor.html?vehicle_no_color='+str+'" target="_blank" style="color:blue;">'+val+'</a>', val);
		this.setCValue(val, val);
	}
}
eXcell_TrackingBtn.prototype = new eXcell;  

function eXcell_carStatus(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon all-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		if(val == 1){
			val = "运行";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon run-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}else if(val == 2){
			val = "停车";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon stop-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}else if(val == 3){
			val = "掉线";
			handleStr = '<div style="line-height:30px;margin-top:6px;"><div class="dn">'+val+'</div><div class="staues-icon dropped-icon" style="padding:0;margin:0 auto;width:8px;height:8px;"></div></div>';
		}
		this.setCValue(handleStr, val);
	}
	
};
eXcell_carStatus.prototype = new eXcell;

//自定义操作列
function eXcell_cancelBtn(cell){
	if(cell){
		this.cell = cell;
		this.grid = this.cell.parentNode.grid;
	}
	this.edit = function(){}
	this.isDisable = function(){return true;}
	this.setValue = function(val){
		var vehicleId = val;
		var handleStr = "";	
		//var vehicle_no_color = index.base64.encode(index.vehicleNoColor.get(vehicleId));
		if(index.GlobelVehicle.get(vehicleId)!=null&&index.GlobelVehicle.get(vehicleId).isPublicNet>0){
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'
							/*+'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<a href="'+appCtx+'video/videoMonitor.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/video.png" title="视频监控" onclick="showVideo('+vehicleId+')" /></a>'+
							'</div>'+
							'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<a href="'+appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" /></a>'+
							'</div>'*/; 				
		}else{
			handleStr = '<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
								'<img src="'+global.url.domain+'gps-web/resources/images/cancelSub.png" title="取消" onclick="cancelTrack('+vehicleId+')" />'+
							'</div>'
							/*+'<div style="padding:0px;float:left;width:33%;height:19px;cursor:pointer;text-align:center;">'+
							'<a href="'+appCtx+'gis/playback/trackPlayBack.html?vehicle_no_color='+vehicle_no_color+'" target="_blank"><img src="'+global.url.domain+'gps-web/resources/images/track.png" title="轨迹回放" /></a>'+
							'</div>'*/;
		}	
		this.setCValue(handleStr, val);
	}
}
eXcell_cancelBtn.prototype = new eXcell;
